package com.kkb.javawebtest.servlet;

import com.kkb.javawebtest.DBUtils.DBUtils;
import com.kkb.javawebtest.bean.User;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @author whl
 * @date 2021/8/31 @14:04
 */

public class LoginServlet extends HttpServlet {
    public LoginServlet() {
        super();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("初始化");
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");


        DBUtils dbUtils = new DBUtils();

        String sql = "select * from user where name =? and password =?";

        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");


        ArrayList list = new ArrayList();
        list.add(userName);
        list.add(userPassword);

        ResultSet resultSet = dbUtils.query(sql, list);
        User user = null;
        ArrayList<User> arrayList = new ArrayList<>();
        try {
            while (resultSet.next()){
                user = new User();
                user.setName(resultSet.getString("name"));
                user.setPassword(resultSet.getString("password"));
                arrayList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbUtils.closedAll();

        }
        for (User arr : arrayList) {
            if (userName.equals(arr.getName())&&userPassword.equals(arr.getPassword())){
                //req.getRequestDispatcher("/success.html").forward(req,resp);

                HttpSession session = req.getSession();
                session.setAttribute("userName",userName);

                resp.sendRedirect("/success.jsp");
                return;
            }
        }
        //req.getRequestDispatcher("/fail.html").forward(req,resp);


        resp.sendRedirect("/fail.html");
    }

    @Override
    public void destroy() {
        System.out.println("服务器关闭");
    }

}
